<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/8
 * Time: 11:10
 */

namespace common\service;
use yii\data\Pagination;

class DataService extends BaseService
{
    public $_model = null; //模型类的实例
    public function __construct($model)
    {
        $this->_model = $model;
    }

    /**
     *    通过condition查询数据,condition参数可以是数组
     *    数据查询 通用方法封装
     */
    public function getDataByCondition($condition, $page_size = 20, $page = 0, $relation = "", $order = "",$isCalculate = true)
    {
        $count = 0;
        $pages = null;

        if($page_size != "" && $isCalculate){
            if(empty($relation)){
                $count = $this->_model->find()->where($condition)->count();
            }else{
                $count = $this->_model->find()->where($condition)->with($relation)->count($condition);
            }

            $pages = new Pagination(['totalCount' => $count]);
            $pages->pageSize = $page_size;
            $pages->setPage($page);

            $pages_info['page'] = $pages->getPage();
            $pages_info['page_count'] = $pages->getPageCount();
            $pages_info['page_size'] = $pages->getPageSize();
            $pages_info['offset'] = $pages->getOffset();
            $pages_info['limit'] = $pages->getLimit();
        }

        if(empty($relation)){
            $data = $this->_model->find()->where($condition)->offset($pages->offset)->limit($pages->limit)->orderBy($order)->asArray()->all();
        }else{
            $data = $this->_model->find()->where($condition)->offset($pages->offset)->limit($pages->limit)->with($relation)->orderBy($order)->asArray()->all();
        }



        return array("count" => $count, "pages" => $pages, "data" => $data);
    }


    /**
     *  根据某个字段 in 查询
     *  $data  传入数组
     *  $relate_model  传入关系模型
     *  $id_column  数组的关联字段
     *  $pk_column  模型的关联字段
     *  $name_columns  需要查询的字段
     */
    public static function getDicByRelateID($data,$relate_model,$id_column,$pk_column,$name_columns = [])
    {
        $_ids = [];
        $_names = [];
        foreach($data as $_row)
        {
            $_ids[] = $_row[$id_column];
        }
        $rel_data = $relate_model::findAll([$pk_column => array_unique($_ids)]);
        foreach($rel_data as $_rel)
        {
            $map_item = [];
            if($name_columns && is_array($name_columns)){
                foreach($name_columns as $name_column){
                    $map_item[$name_column] = $_rel->$name_column;
                }
            }
            $_names[$_rel->$pk_column] = $map_item;
        }
        return $_names;
    }


}